package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.AudioLike;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 实现喜欢用户语音的接口
 */
@Service(version = "1.0.0")
@Slf4j
public class LikeAudioApiImpl implements LikeAudioApi {
    //redis中储存喜欢的用户语音的key
    public static final String LIKE_USER_AUDIO = "AUDIO_LIKE_";
    //注入redis模板
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //注入mongodb模板
    @Autowired
    private MongoTemplate mongoTemplate;

    //喜欢某条语音
    @Override
    public Boolean likeThisAudio(String sendUserId, String soundUrl, Long userId) {
        //判断redis中是否存在数据
        String key = LIKE_USER_AUDIO + userId;
        String hashKey = String.valueOf(soundUrl);
        try {
            if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                log.info("redis有数据了");
                //有数据，说明已经喜欢过这个语音了
                return false;
            }
            //没数据,先保存到数据库，在保存到redis
            AudioLike audioLike = new AudioLike();
            audioLike.setId(ObjectId.get());
            audioLike.setUserId(userId);
            audioLike.setSendUserId(Convert.toLong(sendUserId));
            audioLike.setUrl(soundUrl);
            audioLike.setCreated(System.currentTimeMillis());
            //1.保存到数据库
            mongoTemplate.save(audioLike);
            //2.放redis
            redisTemplate.opsForHash().put(key, hashKey, sendUserId);
            return true;
        } catch (Exception e) {
            log.error("数据保存失败" + e);
        }

        return false;
    }


    //判断是否相互喜欢
    //第一次 2    1   第二次 1    2
    @Override
    public Boolean isMutualLike(String sendUserId, String soundUrl, Long userId) {
        //第一次的redis,现在是第二次访问
        String key1 = LIKE_USER_AUDIO + sendUserId;  //1  url  2
        String hashKey1 = String.valueOf(soundUrl);
        //第二次的redis,现在是第二次访问
        String key2 = LIKE_USER_AUDIO + userId;  //2  url 1
        String hashKey2 = String.valueOf(soundUrl);
        String s1 = String.valueOf(redisTemplate.opsForHash().get(key1, hashKey1)); //2
        String s2 = String.valueOf(redisTemplate.opsForHash().get(key2, hashKey2)); // 1
        return StringUtils.equals(s1, String.valueOf(userId)) && StringUtils.equals(s2, sendUserId);

    }
}
